package ex.hql.config;

import ex.hql.utils.JwtTokenUtil;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.beans.factory.annotation.Qualifier;
import org.springframework.beans.factory.annotation.Value;
import org.springframework.context.annotation.Configuration;
import org.springframework.messaging.Message;
import org.springframework.messaging.MessageChannel;
import org.springframework.messaging.simp.config.ChannelRegistration;
import org.springframework.messaging.simp.config.MessageBrokerRegistry;
import org.springframework.messaging.simp.stomp.StompCommand;
import org.springframework.messaging.simp.stomp.StompHeaderAccessor;
import org.springframework.messaging.support.ChannelInterceptor;
import org.springframework.messaging.support.MessageHeaderAccessor;
import org.springframework.security.authentication.UsernamePasswordAuthenticationToken;
import org.springframework.security.core.context.SecurityContextHolder;
import org.springframework.security.core.userdetails.UserDetails;
import org.springframework.security.core.userdetails.UserDetailsService;
import org.springframework.util.StringUtils;
import org.springframework.web.socket.config.annotation.EnableWebSocketMessageBroker;
import org.springframework.web.socket.config.annotation.StompEndpointRegistry;
import org.springframework.web.socket.config.annotation.WebSocketMessageBrokerConfigurer;

/**
 * @program:yeb
 * @author: hql
 * @Time: 2021/9/9  10:28
 * @description: websocket配置类
 */
@Configuration
@EnableWebSocketMessageBroker
public class WebSocketConfig implements WebSocketMessageBrokerConfigurer {

    @Value("${jwt.tokenHead}")
    private String tokenHead;

    @Autowired
    private JwtTokenUtil jwtTokenUtil;

    @Autowired
    @Qualifier("myUserDetailService")
    private UserDetailsService userDetailsService;

    /**
     * 配置websocket服务地址,并且指定是否使用webSockJs
     * @param registry
     */
    @Override
    public void registerStompEndpoints(StompEndpointRegistry registry) {
        /**
         * 1 将 /ws/ep 路径注册为stomp的端点，用户连接了这个端点就可以进行websocket通信
         * 2 setAllowedOriginPatterns("*") 允许跨域
         */
        registry.addEndpoint("/ws/ep").setAllowedOriginPatterns("*").withSockJS();
    }

    /**
     * 输入通道参数配置
     * @param registration
     */
    @Override
    public void configureClientInboundChannel(ChannelRegistration registration) {
                registration.interceptors(new ChannelInterceptor() {
                    @Override
                    public Message<?> preSend(Message<?> message, MessageChannel channel) {
                        StompHeaderAccessor accessor = MessageHeaderAccessor.getAccessor(message, StompHeaderAccessor.class);
                        //判断是否为连接，如果是，需要获取token,并且设置用户对象
                        if(StompCommand.CONNECT.equals(accessor.getCommand())){
                            String header = accessor.getFirstNativeHeader("Auth-Token");
                            if(!StringUtils.isEmpty(header)){
                                String authToken = header.substring(tokenHead.length());
                                String name = jwtTokenUtil.getUserNameFromToken(authToken);
                                if(!StringUtils.isEmpty(name)){
                                    //登入
                                    UserDetails userDetails = userDetailsService.loadUserByUsername(name);
                                    //验证token是否有效,重新设置用户对象
                                    if(jwtTokenUtil.ValidateToken(authToken,userDetails)){
                                        UsernamePasswordAuthenticationToken authenticationToken = new UsernamePasswordAuthenticationToken(userDetails, null, userDetails.getAuthorities());
                                        SecurityContextHolder.getContext().setAuthentication(authenticationToken);
                                        accessor.setUser(authenticationToken);
                                    }
                                }

                            }
                        }
                        return message;
                    }
                });
    }

    /**
     * 配置消息代理
     * @param registry
     */
    @Override
    public void configureMessageBroker(MessageBrokerRegistry registry) {
        //配置代理域，配置代理目的地址的前缀为 /queue ，可以在配置域上向客户端发送消息
        registry.enableSimpleBroker("/queue");
    }
}
